const user = require("../database/user");
const md5 = require("md5");
const jwt = require("jsonwebtoken");

module.exports = async (req,res,next)=>{
    const {username, password, tel} = req.query;

    const where = {};
    if(username) where.username = username;
    if(tel) where.tel = tel;

    const data = await user.find(where, {_id:0,__v:0});

    if(data.length < 1){
        res.send({
            code:0,
            msg:"用户名不存在"
        });
    }else if( data[0].password === md5(password) ){
        // 用户状态存储：cookie, session, token

        // cookie技术
        // res.cookie("isLogin", "ok");
        // res.cookie("userId", "anhgsvfdhgfnhgj");
        // res.cookie("username", "anhgsvfdhgfnhgj");

        // session技术
        // req.session.isLogin = "jhagfusdhihflny";
        // req.session.userId = "jhagfusdhihflny";
        // req.session.username = "jhagfusdhihflny";

        // token技术 - 生成了一串token
        const tokenStr = jwt.sign({
            userId: data[0].userId
        }, "千锋H5", {
            expiresIn: 60 * 30
        });

        res.send({
            code:1,
            msg:"登录成功",
            token:tokenStr,      // 将token字符响应给前端
            data: data[0]        // 登录成功后，将当前用户信息响应给前端
        });
    }else{
        res.send({
            code:2,
            msg:"密码不对"
        });
    }
}